package  AIRProject.filemanager
{
	import utils.Alert;
	import com.adobe.images.*;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.ByteArray;
	/**
	 * ...
	 * @author FireKnight
	 */
	public class SavePic 
	{
		
		public function SavePic() 
		{
			
		}
		
		public static function jpg(_bm:Bitmap,name:String,quality:uint,folder:File=null):void
		{
			if(folder==null)
			{
				folder=File.applicationStorageDirectory;
			}
			var bmpd:BitmapData = new BitmapData(_bm.width,_bm.height,true,0x00FFFFFF);
			bmpd.draw(_bm);
			var jpgenc:JPGEncoder = new JPGEncoder(quality);
			var imgByteArray:ByteArray = jpgenc.encode(bmpd)
			saveFile(imgByteArray,folder,name,"jpg");
			
		}
		
		public static function png(_bm:Bitmap,name:String,folder:File=null):void
		{
			if(folder==null)
			{
				folder=File.applicationStorageDirectory;
			}
			var bmpd:BitmapData = new BitmapData(_bm.width,_bm.height,true,0x00FFFFFF);
			bmpd.draw(_bm);
			var imgByteArray:ByteArray = PNGEncoder.encode(bmpd);
			saveFile(imgByteArray,folder,name,"png");
		}
		
		public static function saveFile(data:ByteArray,folder:File,name:String,type:String):void
		{
			
			var file:File=folder.resolvePath(folder.url+"//"+name+"."+type);
			var fs:FileStream = new FileStream();
			try
			{
				//open file in write mode
				fs.open(file,FileMode.WRITE);
				//write bytes from the byte array
				fs.writeBytes(data);
				//close the file
				fs.close();
			}
			catch(e:Error)
			{
				Alert.show(e.message);
			}
		}
		
	}

}